
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.properties import BooleanProperty, ListProperty, ObjectProperty, StringProperty, NumericProperty
from kivy.core.window import Window
import os.path

## def _(a):
##     return a

import guiCommon
#import wineAreas
from kivyext.treegridview import MyListView
import levinCommon
from levinCommon import dateFromOrdinal

class DisplayLabel(guiCommon.CompactLabel):
    pass

class WineDetailKeys(guiCommon.CompactLabel):
    pass
class WineDetailValue(guiCommon.CompactLabel):
    pass



class WineDetailFormat(object):
    def __init__(self, key, title):
        self.key = key
        self.title = title
    def listViewEntry(self):
        keyLab, vLab = WineDetailKeys(text=self.title),WineDetailValue(text='')
        self.vLab = vLab
        self.kLab= keyLab
        return [keyLab, self.vLab]
    def update(self, bottle):
        print ' updating display ', self.key , getattr(bottle, self.key)
        self.vLab.text = unicode(getattr(bottle, self.key))

class WineDetailDebug(WineDetailFormat):
    def listViewEntry(self):
        keyLab, vLab = WineDetailKeys(text="a"),WineDetailValueD(text='')
        self.vLab = vLab
        self.kLab= keyLab
        return [keyLab, self.vLab]

    def update(self, bottle):
        print ' --- updating display ', self.key , getattr(bottle, self.key)
        v = unicode(getattr(bottle, self.key))
        self.vLab.text = v # u"a\xe9 a"+str(bottle.numInStock)
        #self.vLab.text = unicode(getattr(bottle, self.key))
        print '           ---> ',self.vLab.text , self.vLab.size
    
class WineDetailRange(WineDetailFormat):
    def update(self, bottle):
        amin = bottle.optimalMin
        amax = bottle.optimalMax
        if amin and amax:
            self.vLab.text = _(u"%d to %d"%(amin,amax))
        elif amin:
            self.vLab.text = str(amin)
        elif amax:
            self.vLab.text = str(amax)
        else:
            self.vLab.text = ""

class WineDetailRate(WineDetailFormat):
    def update(self, bottle):
        r = bottle.meanrate
        if r is None :
            self.vLab.text = "-"
        else:
            self.vLab.text = str(r) + " /10"


from datetime import date as DateObj
class WineDetailAcquire(WineDetailFormat):
    def update(self, bottle):
        date = dateFromOrdinal(bottle.acquireDate)
        comm = bottle.acquireComment
        t = date+'. ' if date else ''
        self.vLab.text = t + (comm if comm else '')
            
_wineDetailsList = [
WineDetailRate("meanrate" , _( "Rate" )),
WineDetailFormat("cepage" , _( "Grape variety" )),
WineDetailRange("optimalMin", _("Optimal years") ),
WineDetailFormat("numInStock" , _( "Bottles" )),  
WineDetailAcquire("acquireComment" , _( "Acquire" )),
WineDetailFormat("otherInfo" , _( "Description" )), 
WineDetailFormat("pricePerBottle" , _( "Price" )), 
WineDetailFormat("productor" , _( "Productor" )),  

    ]
    
#class WineDisplay(BoxLayout, guiCommon.BottleWidget):
class WineDisplay(FloatLayout, guiCommon.BottleWidget):
    #bottle = ObjectProperty(None)
    topBox = ObjectProperty(None)
    detailsBox = ObjectProperty(None)
    buttonBar  = ObjectProperty(None)
    mainWidgets = ListProperty([])

    spacing = NumericProperty(4)
    image_src = StringProperty("")
    
    #appellation_lab = ObjectProperty(None)
    def __init__(self, **kargs):
        super(WineDisplay,self).__init__(**kargs)

        detailsListV = MyListView( num_columns=2,columns_width_force=[0.4,0.6],
                                 entries = [d.listViewEntry() for d in _wineDetailsList] , size_hint=(1,1),
                                 none_selectable=True)
        detailsListV.setDebugPrefix('wDisplay')
        self.detailsBox.add_widget(detailsListV)
        self.detailsListV = detailsListV
        guiCommon.commonEvents.bind(on_bottle_edited= self.bottle_edited) 

    def on_bottle(self, i, bottle):
        self.mainWidgets[0].text = bottle.appellation
        self.mainWidgets[1].text = bottle.cru_name+',  '+str(bottle.millesime)
        for f in _wineDetailsList:            
            f.update(bottle)
        if os.path.exists( self.bottleImagePath()):
            self.image_src = self.bottleImagePath()
        else:
            self.image_src = levinCommon.LEVIN_ICONS_NOPIC
            
    def bottle_edited(self,i,bottle):
        print ' ========== bottle_edited'
        if bottle != self.bottle:
            self.bottle = bottle
        else:
            self.on_bottle(None, bottle)


    def start_add_image(self, *l):

        askCam = guiCommon.LeVinAlertModal(alertText=_('Picture from camera or file ?') , validText=_('Camera'), cancelText=_('File'),
                                           cancelCallBack = self.addImageFromFile,
                                           validCallBack = self.addImageFromCamera).open()

    def addImageFromCamera(self, *l):
        def done(im):
            im.camera.texture.save("tmp.png", False)
            self.update_image("tmp.png")
        getCam = guiCommon.CameraCapture(doneCallBack =done )
        getCam.open()
        print 'addImageFromCamera', l, getCam.camera.resolution

    def addImageFromFile(self, *l ):
        from kivy.uix.filechooser import FileChooserIconView
        f = FileChooserIconView(filters=[ '*png', '*jpeg','*JPEG', '*jpg', '*JPG' ], path=levinCommon.application.config.get('Paths', 'Images'))
        pop =  guiCommon.LeVinAlert(content=f, title=_('Choose image') , size_factor=2./3, validText='') #, size_hint=(None,None),size=(Window.width*2/3,Window.height*2/3))

        def file_chosen(*l):
            theF = f.selection[0]
            pop.dismiss()
            self.update_image(theF)
        f.bind( on_submit = file_chosen)
        pop.validB.bind( on_press = file_chosen)
        pop.cancelB.bind( on_release = pop.dismiss)
        print 'XXX opened file choser !', pop
        pop.open()
        


    def bottleImagePath(self):
        return os.path.join(levinCommon.USER_DATA_DIR, str(self.bottle.bottleId)+'_pic.jpeg')
    
    def update_image(self, imageF):
        levinCommon.application.config.setdefault('Paths', 'Images', os.path.dirname( imageF))
        levinCommon.application.config.set('Paths', 'Images', os.path.dirname( imageF))
        levinCommon.buildUserDataDir()
        from kivyext.miniimageeditor import ImageEditor
        imEd = ImageEditor(img_src = imageF)
        
        pop =  Popup(content=imEd, title=_('Edit image for %(wine)s')%{'wine':self.bottle.cru_name} )#, size_hint=(None,None),size=(Window.width*2/3,Window.height*2/3))
        #pop =  guiCommon.LeVinAlert(content=imEd, title=_('Edit image for %(wine)s')%{'wine':self.bottle.cru_name}, size_factor=1 )#, size_hint=(None,None),size=(Window.width*2/3,Window.height*2/3))

        print 'XXX about image edit ',pop
        save_name = self.bottleImagePath()
        def save_image(*l):
            imEd.save_image(save_name)
            self.bottle.touch()
            self.image_src = save_name
            pop.dismiss()
        imEd.bind( on_canceled = pop.dismiss,
                   on_validated = save_image)
        
        pop.open()
        print 'XXX about image edit opened',pop
        imEd.cropW.hideLimits()
        
from kivy.factory import Factory
for cls in [DisplayLabel, WineDetailValue, WineDetailKeys]:
    Factory.register(cls.__name__, cls=cls)
from kivy.lang import Builder
guiCommon.load_kv_file('wineDisplay.kv')

